# gen_key_cert.py
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
import datetime, os

key_path = 'localhost.key.pem'
crt_path = 'localhost.crt.pem'

# 1. 生成私钥
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
with open(key_path, 'wb') as f:
    f.write(private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()))

# 2. 构建自签名证书
subject = issuer = x509.Name([
    x509.NameAttribute(NameOID.COMMON_NAME, 'localhost')])
cert = x509.CertificateBuilder().subject_name(subject
    ).issuer_name(issuer
    ).public_key(private_key.public_key()
    ).serial_number(x509.random_serial_number()
    ).not_valid_before(datetime.datetime.utcnow()
    ).not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=365)
    ).sign(private_key, hashes.SHA256())

with open(crt_path, 'wb') as f:
    f.write(cert.public_bytes(serialization.Encoding.PEM))

print('已生成匹配的新文件：', key_path, crt_path)